import { defineStore } from 'pinia';

import appConfig from '../../app.config';

import type { TabBarItem } from '@/types/index';

import { LocalStorageService, SessionStorageService } from '@/utils/storage';

type State = {
  userInfo: TypeObject,
  menus: TypeObject[],
  authKeys: string[],
  tabBars: TabBarItem[],
}

/**
 * @description: 获取有权限的tabBar
 */
export function filterTabBarList(tabBarList: Array<TabBarItem>, authCodes: Array<any>) {
  return tabBarList.filter((tabBar) => tabBar.authCodes.some((authCode) => authCodes.includes(authCode)));
}

export const useUserStore = defineStore('_user', {
  state: (): State => ({
    userInfo: {},
    menus: [],
    authKeys: [],
    tabBars: [],
  }),
  actions: {
    getToken(): Promise<TypeObject> {
      return new Promise((resolve, reject) => {
        try {
          // TODO: 使用自己公司的JS Bridge获取token
          resolve({
            token: Math.random()
          });
        } catch (error) {
          console.error('通过云图梭获取token失败：', error);
          reject(new Error(`泰康用户权限信息失败::${error}`));
        }
      });
    },
    getUserInfo(): Promise<TypeObject> {
      return new Promise((resolve) => {
        // TODO: 调用后端接口获取用户基本信息和权限信息
        const userInfo = {
          authorization: 'TGT-820659-ik8G-Cexfz5NnqAicN-uYh5NuPmjNKRGlu6R6l6B0hha5jV9u9E39wH5X7vrogVuB8M-longhu',
          loginName: 'dony',
          loginTime: 1746978336887,
          userId: '39e9a23d-2a85-4f36-a4ac-cd6118566fa7',
          userName: 'dony',
          realName: '明豪'
        };

        const functions = [
          {
            code: 'FM_COCKPIT',
            id: "46fd4232-e210-480c-b3f4-863f79206345",
            name: "数据看板",
          },
          {
            code: 'FM_META_READING',
            id: "46fd4232-e210-480c-b3f4-863f79206345",
            name: "人工抄表",
          }
        ];

        // 获取所有的authKeys，包括组件下面配置的操作
        const authKeys = functions.map((func: TypeObject) => (func.code));
        this.setAuthKeys(authKeys);
        this.setTabBars(authKeys);
        this.setMenus(functions); // am中配置的菜单和组件
        this.setUserInfo(userInfo); // 设置用户信息

        resolve({
          menus: functions,
          authKeys,
        });
      });
    },
    logout(): Promise<TypeObject> {
      return new Promise((resolve) => {
        // TODO: 调用后端退出登录接口
        LocalStorageService.clear();
        SessionStorageService.clear();
        resolve({
          loginUrl: 'https://dony.online/h5/login',
        });
      });
    },
    setUserInfo(info: TypeObject) {
      this.userInfo = info;
      SessionStorageService.set('_user_info', info);
    },
    setMenus(data: TypeObject[]) {
      this.menus = data;
    },
    setAuthKeys(data: string[]) {
      this.authKeys = data;
    },
    setTabBars(data: string[]) {
      this.tabBars = filterTabBarList(appConfig?.tabBar?.list, data);
    },
  },
});
